package services

import (
	log "github.com/sirupsen/logrus"
	"go_anime_picture_api/models/gitee"
	"go_anime_picture_api/models/picture"
	"go_anime_picture_api/utils"
	"math/rand"
	"regexp"
	"strings"
	"time"
)

var (
	sourceMap = map[string]string{
		"":         "https://www.pixiv.net/artworks/",
		"yande":    "https://yande.re/post/show/",
		"danbooru": "https://danbooru.donmai.us/posts/",
		"konachan": "https://konachan.com/post/show/",
		"sankaku":  "https://chan.sankakucomplex.com/ko/post/show/",
	}
	sourceReg = regexp.MustCompile("^(\\D*)(\\d+)")
)

const (
	animePicGiteeUrl = "https://gitee.com/api/v5/repos/anime_picture/anime-picture/contents/picture?access_token=16a415e183b8a8da461db30b8ee0ff83&ref=master"
)

// 构建数据库（暂时用list代替）
func BuildAnimePicInfos() {
	ReBuildAnimePicInfos()
}

// 重构数据库（暂时用list代替）
func ReBuildAnimePicInfos() {

	rand.Seed(time.Now().UnixNano())
	picture.AnimePicInfos = picture.AnimePicInfoList{}

	infos := GetFileInfos(animePicGiteeUrl)
	dealAnimePicInfosByGitee(&infos, &picture.AnimePicInfos)

	log.Infoln("构建动漫图片数据库完成")
}

func RandomAnimePicInfo() picture.AnimePicInfo {
	return picture.AnimePicInfos[rand.Intn(len(picture.AnimePicInfos))]
}

func dealAnimePicInfosByGitee(infos *gitee.FileInfoList, animePicInfos *picture.AnimePicInfoList) {
	// 读取文件
	for i := 0; i < len(*infos); i++ {
		info := (*infos)[i]

		// 根据“-”分割信息并保存到List中
		fileFullName := info.Name
		fileName, _ := utils.GetFileNameAndExt(fileFullName)
		fileNameInfo := strings.Split(fileName, "-")
		group := sourceReg.FindStringSubmatch(fileNameInfo[1])
		if len(group) == 0 {
			log.Error("文件名错误，无法查找到source信息：" + fileName)
			continue
		}
		source, exist := sourceMap[group[1]]
		if !exist {
			source = "无来源"
		} else {
			source += group[2]
		}
		// 设置每张图片的信息
		animePicInfo := picture.AnimePicInfo{
			Name:      fileFullName,
			Url:       info.DownloadUrl,
			Artist:    fileNameInfo[0],
			Source:    source,
			Copyright: fileNameInfo[2],
		}
		*animePicInfos = append(*animePicInfos, animePicInfo)

	}
}
